﻿using System;
using System.Linq;
using System.Text;

namespace DataScripter.Export.Code
{
	class CodeBuilder
	{
		private int _indentation;
		private string _indentationString = string.Empty;
		public int Indentation
		{
			get { return _indentation; }
			set
			{
				_indentation = value;
				_indentationString = _indentation == 0 ? string.Empty : string.Empty.PadRight(_indentation);
			}
		}

		private readonly StringBuilder _builder = new StringBuilder();

		public CodeBuilder() : this(0){}
		public CodeBuilder(int indentation)
		{
			Indentation = indentation;
		}

		public void AppendLine()
		{
			_builder.AppendLine();
		}

		public void AppendLine(string lineToAppend)
		{
			Indent();
			_builder.AppendLine(lineToAppend);
		}

		public void AppendLine(string format, params object[] parameters)
		{
			Indent();
			_builder.AppendLine(string.Format(format, parameters));
		}

		private void Indent()
		{
			_builder.Append(_indentationString);
		}

		public override string ToString()
		{
			return _builder.ToString();
		}

		public void AppendLines(string exportedCode)
		{
			string[] lines = exportedCode.Split((char)10);
			foreach (string s in lines.Select(line => line.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries)).SelectMany(strings => strings))
			{
				AppendLine(s);
			}
		}

		public void Append(string s)
		{
			Indent();
			_builder.Append(s);
		}
	}
}
